<template>
    <view class="live-camera" :style="{ width: windowWidth, height: windowHeight }">
        <view class="preview" :style="{ width: windowWidth, height: windowHeight}">
            <live-pusher id="livePusher" ref="livePusher" class="livePusher" mode="FHD" beauty="0" whiteness="0"
                :aspect="aspect" min-bitrate="1000" audio-quality="16KHz" device-position="back" auto-focus="false"
                muted="true" :enable-camera="true" :enable-mic="false" :zoom="false" @statechange="statechange"
                :style="{ width: windowWidth, height: windowHeight }"></live-pusher>
            <!--提示语-->
            <cover-view class="remind">
                <!-- <text class="remind-text remind-name" style="">{{ username }}</text> -->
                <!-- <text class="remind-text remind-address" style="">{{ address }}</text> -->
                <text class="remind-text remind-time" style="">{{ time }}</text>
            </cover-view>
        </view>
        <view class="menu">
            <!--底部菜单区域背景-->
            <cover-image class="menu-mask" src="@/static/111.png" style="width: 80rpx;height: 80rpx;background-color: red;"></cover-image>

            <!--返回键-->
            <cover-image class="menu-back" @tap="back" src="@/static/logo.png" style="width: 80rpx;height: 80rpx;background-color: red;"></cover-image>

            <!--快门键-->
            <cover-image class="menu-snapshot" @tap="snapshot" src="@/static/1.png" style="width: 80rpx;height: 80rpx;background-color: red;"></cover-image>

            <!--反转键-->
            <cover-image class="menu-flip" @tap="flip" src="@/static/camear.png" style="width: 80rpx;height: 80rpx;background-color: red;"></cover-image>
        </view>
    </view>
</template>

<script>
    let _this = null;
    export default {
        data() {
            return {
                dotype: 'watermark',
                message: 'live-camer', //水印内容
                username: '',
                address: '无法获取地址',
                time: '2022-2-14 10:23',
                poenCarmeInterval: null, //打开相机的轮询
                aspect: '2:3', //比例
                windowWidth: '', //屏幕可用宽度
                windowHeight: '', //屏幕可用高度
                camerastate: false, //相机准备好了
                livePusher: null, //流视频对象
                snapshotsrc: null ,//快照,
                timer:null,//定时器
            };
        },
        onLoad(e) {
            _this = this;
            if (e.dotype != undefined) this.dotype = e.dotype;
            this.initCamera();
        },
        onReady() {
            // this.getAddress();
            let date = new Date()
            this.time= this.dateFormat("YYYY-mm-dd HH:MM", date);
            this.livePusher = uni.createLivePusherContext('livePusher', this);
            this.startPreview(); //开启预览并设置摄像头
            this.poenCarme();
        },
        onShow() {
            clearInterval(this.timer)
            // 每隔10秒刷新地址和时间
            this.timer = setInterval(()=>{
                // this.getAddress();
                let date = new Date()
                this.time= this.dateFormat("YYYY-mm-dd HH:MM", date);
            },10000);
        },
        onUnload(){
            clearInterval(this.timer)
        },
        methods: {
            getAddress(){
                // uni.getLocation({
                //     type: 'gcj02',
                //         geocode: true,
                //         isHighAccuracy:true,
                //     success:(res) => {
                //                 this.address = res.address.province+res.address.city+res.address.district+res.address.street+res.address.streetNum+res.address.poiName;
                //         console.log('当前位置：' , this.address);
                //                 console.log('当前位置的经度：' + res.longitude);
                //         console.log('当前位置的纬度：' + res.latitude);
                //     }
                // });
            },
            //轮询打开
            poenCarme() {
                //#ifdef APP-PLUS
                if (plus.os.name == 'Android') {
                    this.poenCarmeInterval = setInterval(function() {
                        console.log(_this.camerastate);
                        if (!_this.camerastate) _this.startPreview();
                    }, 2500);
                }
                //#endif
            },
            //初始化相机
            initCamera() {
                uni.getSystemInfo({
                    success: function(res) {
                        _this.windowWidth = res.windowWidth;
                        _this.windowHeight = res.windowHeight;
                        let zcs = _this.aliquot(_this.windowWidth, _this.windowHeight);
                        _this.aspect = _this.windowWidth / zcs + ':' + _this.windowHeight / zcs;
                        console.log('画面比例：' + _this.aspect,'windowWidth',res.windowWidth,res.windowHeight);
                    }
                });
            },

            //整除数计算
            aliquot(x, y) {
                if (x % y == 0) return y;
                return this.aliquot(y, x % y);
            },

            //开始预览
            startPreview() {
                this.livePusher.startPreview({
                    success: a => {
                        console.log(a);
                    }
                });
            },

            //停止预览
            stopPreview() {
                this.livePusher.stopPreview({
                    success: a => {
                        _this.camerastate = false; //标记相机未启动
                    }
                });
            },

            //状态
            statechange(e) {
                //状态改变
                console.log(e);
                if (e.detail.code == 1007) {
                    _this.camerastate = true;
                } else if (e.detail.code == -1301) {
                    _this.camerastate = false;
                }
            },

            //返回
            back() {
                uni.navigateBack();
            },

            //抓拍
            snapshot() {
				console.log('1111','抓拍')
                this.livePusher.snapshot({
                    success: e => {
						console.log('图片，',e.message.tempImagePath)
                        _this.snapshotsrc = e.message.tempImagePath;
                        _this.stopPreview();
                        _this.setImage();
                        uni.navigateBack();
                    },
					fail:e=>{
						console.log('图片，error',e)
					}
                });
            },

            //反转
            flip() {
                this.livePusher.switchCamera();
            },

            //设置
            setImage() {
                let pages = getCurrentPages();
                let prevPage = pages[pages.length - 2]; //上一个页面

                //直接调用上一个页面的setImage()方法，把数据存到上一个页面中去
                prevPage.$vm.watermark({
                    path: _this.snapshotsrc,
                    info: {
                        username: this.username, 
                        address: this.address,
                        time: this.time
                    }
                });
            },
            dateFormat(fmt, date) {
              let ret;
              const opt = {
                "Y+": date.getFullYear().toString(),        // 年
                "m+": (date.getMonth() + 1).toString(),     // 月
                "d+": date.getDate().toString(),            // 日
                "H+": date.getHours().toString(),           // 时
                "M+": date.getMinutes().toString(),         // 分
                "S+": date.getSeconds().toString()          // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
              };
              for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                  fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                };
              };
              return fmt;
            },
        }
    };
</script>

<style lang="less">
    .live-camera {
        justify-content: center;
        align-items: center;

    }

    .preview {
        justify-content: center;
        align-items: center;

    }

    .remind {
        position: absolute;
        top: 80rpx;
        left: 20rpx;
        
        z-index: 100;
    }

    .remind-text {
        color: #dddddd;
        
        width: 710rpx;
    }
    .remind-name{
        font-size: 40rpx;
    }
    .remind-address{
        font-size: 36rpx;
    }
    .remind-time{
        font-size: 30rpx;
    }
    

    .menu {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 750rpx;
        height: 180rpx;
        z-index: 98;
        align-items: center;
        justify-content: center;
    }

    .menu-mask {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 750rpx;
        height: 180rpx;
        z-index: 98;
    }

    .menu-back {
        position: absolute;
        left: 30rpx;
        bottom: 50rpx;
        width: 80rpx;
        height: 80rpx;
        z-index: 99;
        align-items: center;
        justify-content: center;
    }

    .menu-snapshot {
        width: 130rpx;
        height: 130rpx;
        z-index: 99;
    }

    .menu-flip {
        position: absolute;
        right: 30rpx;
        bottom: 50rpx;
        width: 80rpx;
        height: 80rpx;
        z-index: 99;
        align-items: center;
        justify-content: center;
    }
</style>